let pixilipsync;

let proton;
let fireEmitter;
let coinEmitter;
var goldFrame;
let celedone = false;
var socket = io('http://lzweb.dwtv.tv:3042');
//var socket = io('http://127.0.0.1:3042');
var voice_array = [];
var current_audio_path = "";
var sleep = time=>new Promise(resolve=>setTimeout(resolve,time));
// setInterval(()=>{
//     EventBus.dispatch('win')
// },30000)
//https://github.com/krasimir/EventBus
socket.on('connect', function(){
    console.log("connected");
});
socket.on('m:win', (data) => {
    EventBus.dispatch('win')
});
socket.on('m:answer', (data) => {
    if(!!data.message_path){
        voice_array.push(data.message_path);
    }
    voice_array.push(data.filepath);
    current_audio_path = voice_array.shift();
    EventBus.dispatch('playsound',current_audio_path)
});
EventBus.addEventListener("playsoundended", async(data) => {
    //删除current
    if(voice_array.length>0){
        socket.emit("m:delete_voice",current_audio_path);
        await sleep(1500);
        current_audio_path = voice_array.shift();
        EventBus.dispatch('playsound',current_audio_path)
      }else{
        socket.emit("m:delete_voice",current_audio_path);
      }
});

(function (pixilipsync) {
    PIXI.loader
        .add('moc', "/lipsync/assets/haru/haru.moc3", { xhrType: PIXI.loaders.Resource.XHR_RESPONSE_TYPE.BUFFER })
        .add('texture00', "/lipsync/assets/haru/haru.1024/texture_00.png")
        .add('texture01', "/lipsync/assets/haru/haru.1024/texture_01.png")
        .add('texture02', "/lipsync/assets/haru/haru.1024/texture_02.png")
        .add('background', "/lipsync/assets/mylipsync/background.jpg")
        .add('gold', '/lipsync/assets/goldcoin/gold_anim.json')
        .add('playbutton1', "/lipsync/assets/mylipsync/button.png")
        .add('physics', "/lipsync/assets/haru/Physics.physics3.json", { xhrType: PIXI.loaders.Resource.XHR_RESPONSE_TYPE.JSON })
        .add('motion', "/lipsync/assets/haru/motions/haru_idle_03.motion3.json", { xhrType: PIXI.loaders.Resource.XHR_RESPONSE_TYPE.JSON })
        .add('emptymotion', "/lipsync/assets/Common/empty.motion3.json", { xhrType: PIXI.loaders.Resource.XHR_RESPONSE_TYPE.JSON })
        .load(function (loader, resources) {
            var app = new PIXI.Application(1280, 720, { backgroundColor: 0x1099bb });
            document.body.appendChild(app.view);

            var addGlodAnim = () => {
                var frames = [];
                for (var i = 1; i <= 6; i++) {
                    frames.push(PIXI.Texture.fromFrame('gold_' + i + '.png'));
                }
                goldFrame = frames;
            }
            var addProton = () => {
                proton = new Proton;
                renderer = new Proton.PixiRenderer(app.stage);
                var create = renderer.pool.create;
                renderer.pool.create = function (body, particle) {
                    if (body.name == 'COIN') {
                        var glodAnim = new PIXI.extras.AnimatedSprite(goldFrame);
                        glodAnim.anchor.set(0.5);
                        glodAnim.animationSpeed = .5;
                        glodAnim.play();
                        return glodAnim;
                    } else {
                        return create.call(proton.pool, body, particle);
                    }
                }

                proton.addRenderer(renderer);
            }

            function addCoin() {
                coinEmitter = new Proton.Emitter();
                coinEmitter.rate = new Proton.Rate(new Proton.Span(2, 3), .1);
                coinEmitter.addInitialize(new Proton.Body({ name: 'COIN' }));
                coinEmitter.addInitialize(new Proton.Mass(1));
                coinEmitter.addInitialize(new Proton.Life(1.3));
                coinEmitter.addInitialize(new Proton.Velocity(new Proton.Span(3, 5), new Proton.Span(0, 60, true), 'polar'));

                coinEmitter.addBehaviour(new Proton.Rotate(Proton.getSpan(0, 360), new Proton.Span([-1, -2, 0, 1, 2]), 'add'));
                //coinEmitter.addBehaviour(new Proton.Alpha(1, 0));
                coinEmitter.addBehaviour(new Proton.Gravity(6));
                coinEmitter.addBehaviour(new Proton.Scale(Proton.getSpan(.2, .5)));

                //coinEmitter.p.y = 250;
                proton.addEmitter(coinEmitter);
            }
            function addfire() {
                fireEmitter = new Proton.Emitter();
                fireEmitter.rate = new Proton.Rate(new Proton.Span(1, 3), 1);

                fireEmitter.addInitialize(new Proton.Mass(1));
                fireEmitter.addInitialize(new Proton.Radius(2, 4));
                fireEmitter.addInitialize(new Proton.P(new Proton.LineZone(10, app.view.height, app.view.width - 10, app.view.height)));
                fireEmitter.addInitialize(new Proton.Life(1, 1.5));
                fireEmitter.addInitialize(new Proton.V(new Proton.Span(4, 6), new Proton.Span(0, 0, true), 'polar'));

                fireEmitter.addBehaviour(new Proton.Gravity(1));
                fireEmitter.addBehaviour(new Proton.Color('#ff0000', 'random'));
                //fireEmitter.emit();
                proton.addEmitter(fireEmitter);
                renderer = new Proton.PixiRenderer(app.stage);
                /*
                renderer.onProtonUpdate = function () {
                    context.fillStyle = "rgba(0, 0, 0, 0.1)";
                    context.fillRect(0, 0, app.stage.width, app.stage.height);
                };
                */
                //proton.addRenderer(renderer);

                ////NOTICE :you can only use two emitters do this effect.In this demo I use more emitters want to test the emtter's life
                proton.addEventListener(Proton.PARTICLE_DEAD, function (particle) {

                });


            }
            function createFirstEmitter(particle) {
                var subemitter = new Proton.Emitter();
                subemitter.rate = new Proton.Rate(new Proton.Span(250, 300), 1);
                subemitter.addInitialize(new Proton.Mass(1));
                subemitter.addInitialize(new Proton.Radius(1, 2));
                subemitter.addInitialize(new Proton.Life(1, 3));
                subemitter.addInitialize(new Proton.V(new Proton.Span(2, 4), new Proton.Span(0, 360), 'polar'));

                subemitter.addBehaviour(new Proton.RandomDrift(10, 10, .05));
                subemitter.addBehaviour(new Proton.Alpha(1, 0));
                subemitter.addBehaviour(new Proton.Gravity(3));
                var color = Math.random() > .3 ? Proton.MathUtils.randomColor() : 'random';
                subemitter.addBehaviour(new Proton.Color(color));

                subemitter.p.x = particle.p.x;
                subemitter.p.y = particle.p.y;
                subemitter.emit('once', true);
                proton.addEmitter(subemitter);
            }

            function createSecendEmitter(particle) {
                var subemitter = new Proton.Emitter();
                subemitter.rate = new Proton.Rate(new Proton.Span(100, 120), 1);

                subemitter.addInitialize(new Proton.Mass(1));
                subemitter.addInitialize(new Proton.Radius(4, 8));
                subemitter.addInitialize(new Proton.Life(1, 2));
                subemitter.addInitialize(new Proton.V([1, 2], new Proton.Span(0, 360), 'polar'));

                subemitter.addBehaviour(new Proton.Alpha(1, 0));
                subemitter.addBehaviour(new Proton.Scale(1, .1));
                subemitter.addBehaviour(new Proton.Gravity(1));
                var color = Proton.MathUtils.randomColor();
                subemitter.addBehaviour(new Proton.Color(color));

                subemitter.p.x = particle.p.x;
                subemitter.p.y = particle.p.y;
                subemitter.emit('once', true);
                proton.addEmitter(subemitter);
            }
            function spoolcoin() {
                //console.log(celedone)
                //if (celedone) return;
                //fireEmitter.p.x = 100;

                coinEmitter.p.x = 200 + Math.random() * 700 + 20;
                coinEmitter.p.y = 100 + Math.random() * 20 + 20;
                coinEmitter.emit(1.5);
                console.log('send coin')
                //setTimeout(function () { celedone = false }, 1000);
                //celedone = true;
            }
            EventBus.addEventListener("win", onTouchStart);
            EventBus.addEventListener("playsound", (data) => {
                console.log(data);
                let target = data.target;
                webAudio.playurl(data.target)
            });
            EventBus.addEventListener("stopsound", (data) => {
                webAudio.stop()
            });

            function onTouchStart() {
                spoolcoin();
                setTimeout(spoolcoin, 200);
                setTimeout(spoolcoin, 400);
            }
            app.stage.interactive = true;
            app.stage.on('pointerdown', onTouchStart);

            addGlodAnim(loader, resources);
            addProton();
            addCoin();
            addfire();

            //============================================
            console.log('draw background')
            let background_img = PIXI.Sprite.from('background');
            app.stage.addChild(background_img)
            var webAudio = null;
            webAudio = new WebAudio(app);
            var moc = LIVE2DCUBISMCORE.Moc.fromArrayBuffer(resources['moc'].data);
            var model = new LIVE2DCUBISMPIXI.ModelBuilder()
                .setMoc(moc)
                .setTimeScale(1)
                .addTexture(0, resources['texture00'].texture)
                .addTexture(1, resources['texture01'].texture)
                .addTexture(2, resources['texture02'].texture)
                .setPhysics3Json(resources['physics'].data)
                .addAnimatorLayer("base", LIVE2DCUBISMFRAMEWORK.BuiltinAnimationBlenders.OVERRIDE, 1)
                .addAnimatorLayer("lipsync", LIVE2DCUBISMFRAMEWORK.BuiltinAnimationBlenders.OVERRIDE, 1)
                .build();
            app.stage.addChild(model);
            app.stage.addChild(model.masks);
            var animation = LIVE2DCUBISMFRAMEWORK.Animation.fromMotion3Json(resources['motion'].data);
            var emptyAnimation = LIVE2DCUBISMFRAMEWORK.Animation.fromMotion3Json(resources['emptymotion'].data);
            model.animator
                .getLayer("base")
                .play(animation);
            app.ticker.add(function (deltaTime) {
                webAudio.visualize();
                model.update(deltaTime);
                model.masks.update(app.renderer);
                proton.update();
            });


            var onResize = function (event) {
                if (event === void 0) { event = null; }
                var width = window.innerWidth;
                var height = (width / 16.0) * 9.0;
                app.view.style.width = width + "px";
                app.view.style.height = height + "px";
                app.renderer.resize(width, height);
                background_img.width = width;
                background_img.height = height;
                model.position = new PIXI.Point((width * 0.5), (height * 1.2));
                model.scale = new PIXI.Point((model.position.x * 2.2), (model.position.x * 2.2));
                model.masks.resize(app.view.width, app.view.height);
            };
            onResize();
            window.onresize = onResize;
            var onLipsync = function () {
                emptyAnimation.evaluate = function (time, weight, blend, target) {
                    var param_mouth_open_y = target.parameters.ids.indexOf("PARAM_MOUTH_OPEN_Y");
                    if (param_mouth_open_y < 0) {
                        param_mouth_open_y = model.parameters.ids.indexOf("ParamMouthOpenY");
                    }
                    if (param_mouth_open_y >= 0) {
                        var volume = webAudio.getVolume();
                        target.parameters.values[param_mouth_open_y] =
                            blend(target.parameters.values[param_mouth_open_y], volume, 0, weight);
                    }
                };
                model.animator.getLayer("lipsync").play(emptyAnimation);
            };
            onLipsync();
        });
    var WebAudio = (function () {
        function WebAudio(app) {
            this._audioNames = [];
            this._volume = 0;
            this._microphoneMode = false;
            this._nextIndex = 0;
            var _AudioContext = AudioContext || webkitAudioContext;
            this._audioCtx = new _AudioContext();
            this.initCanvas();
            this.drawVolumeUI(app);
            console.log(this._audioCtx);
            this._audioCtx.addEventListener('ended', ()=>{console.log(333)});
            this._audioCtx.addEventListener('complete', this.onComplete);
        }
        WebAudio.prototype.onEnded = function () {
            console.log("on ended")
        }
        WebAudio.prototype.onComplete = function () {
            console.log("on complete")
        }
        WebAudio.prototype.initCanvas = function () {
            this._audioCanvas = document.createElement("canvas");
            this._audioCanvas.id = "visualizer";
            this._audioCanvas.width = 255;
            this._audioCanvas.height = 38;
            this._audioCanvasCtx = this._audioCanvas.getContext("2d");
            this._audioCanvasCtx.clearRect(0, 0, this._audioCanvas.width, this._audioCanvas.height);
            this._audioCanvasCtx.fillStyle = "rgb(0, 0, 0)";
            this._audioCanvasCtx.fillRect(0, 0, this._audioCanvas.width, this._audioCanvas.height);
        };
        WebAudio.prototype.drawVolumeUI = function (app) {
            this._spriteVolume = new PIXI.Sprite(PIXI.Texture.fromCanvas(this._audioCanvas));
            this._spriteVolume.x = 40;
            this._spriteVolume.y = 50;
            console.log("draw volume")
            // app.stage.addChild(this._spriteVolume);
        };
        WebAudio.prototype.setAudio = function (index, audioName) {
            this._audioNames[index] = audioName;
        };
        WebAudio.prototype.playurl = function (url) {
            var _this = this;
            fetch(url).then(function (response) {
                return response.arrayBuffer();
            }).then(function (arraybuffer) {
                return _this._audioCtx.decodeAudioData(arraybuffer);
            }).then(function (buffer) {
                _this.playSound(buffer);
            });
        };
        WebAudio.prototype.play = function (index) {
            var _this = this;
            fetch(this._audioNames[index]).then(function (response) {
                return response.arrayBuffer();
            }).then(function (arraybuffer) {
                return _this._audioCtx.decodeAudioData(arraybuffer);
            }).then(function (buffer) {
                _this.playSound(buffer);
            });
        };
        WebAudio.prototype.nextPlay = function () {
            if (this._nextIndex >= this._audioNames.length) {
                this._nextIndex = 0;
            }
            this.play(this._nextIndex);
            this._nextIndex++;
        };
        WebAudio.prototype.getAudioAccess = function () {
            var _this = this;
            this._microphoneMode = true;
            navigator.mediaDevices.getUserMedia({
                audio: true,
                video: false
            }).then(function (stream) {
                _this._sourceNode = _this._audioCtx.createMediaStreamSource(stream);
                _this._analyser = _this._audioCtx.createAnalyser();
                _this._bufferLengthAlt = _this._analyser.fftSize;
                _this._dataArrayAlt = new Uint8Array(_this._bufferLengthAlt);
                _this._sourceNode.connect(_this._analyser);
            }).catch(function (error) {
                console.log(error);
            });
        };
        WebAudio.prototype.playSound = function (buffer) {
            this._soundSource = this._audioCtx.createBufferSource();
            this._soundSource.addEventListener('ended', ()=>{
                EventBus.dispatch('playsoundended')
            });
            this._soundSource.buffer = buffer;
            this._analyser = this._audioCtx.createAnalyser();
            this._bufferLengthAlt = this._analyser.frequencyBinCount;
            this._dataArrayAlt = new Uint8Array(this._bufferLengthAlt);
            this._soundSource.connect(this._analyser);
            this._analyser.connect(this._audioCtx.destination);
            this._soundSource.start();
        };
        WebAudio.prototype.visualize = function () {
            if (this._analyser == null)
                return;
            this._analyser.getByteFrequencyData(this._dataArrayAlt);
            this._audioCanvasCtx.fillStyle = 'rgb(0, 0, 0)';
            this._audioCanvasCtx.fillRect(0, 0, this._audioCanvas.width, this._audioCanvas.height);
            var barWidth = 0;
            var barHeight = 0;
            if (this._microphoneMode) {
                barHeight = (this._audioCanvas.width / this._bufferLengthAlt) * 300.0;
            }
            else {
                barHeight = (this._audioCanvas.width / this._bufferLengthAlt) * 150.0;
            }
            var maxValue = 0;
            for (var i = 0; i < this._bufferLengthAlt; i++) {
                barWidth = this._dataArrayAlt[i];
                maxValue = maxValue > barWidth ? maxValue : barWidth;
                this._volume = maxValue / 255;
                this._audioCanvasCtx.fillStyle = 'rgb(' + (barWidth + 100) + ',50, 50)';
                this._audioCanvasCtx.fillRect(0, 0, barWidth, barHeight);
            }
            this._spriteVolume.texture.update();
        };
        WebAudio.prototype.getVolume = function () {
            return this._volume;
        };
        WebAudio.prototype.stop = function () {
            this._soundSource.stop();
        };
        return WebAudio;
    }());
})(pixilipsync || (pixilipsync = {}));


$(() => {
    console.log("hehe")
})